package com.caldremch.powerservice;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.nfc.Tag;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

/**
 * @author Caldremch
 * @date 2018-09-30 16:30
 * @describe
 *
 *
 *
 *
 *
 * 则不应在处理完一个启动请求之后立即销毁服务，因为此时可能已经收到了新的启动请求，在第一个请求结束时停止服务会导致第二个请求被终止。
 * 为了避免这一问题，可以使用 stopSelf(int) 确保服务停止请求始终基于最新一次的启动请求。也就是说，
 * 如果调用 stopSelf(int) 方法的参数值与onStartCommand()接受到的最新的startId值不相符的话，stopSelf()方法就会失效，
 * 从而避免终止尚未处理的请求
 **/
public class PowerService extends Service {

    private static final String TAG = "PowerService";

    private MyBinder mBinder = new MyBinder();

    public enum Op{
        START,
        PAUSE,
        STOP
    }


    @Override
    public void onCreate() {
        super.onCreate();
//        Notification.Builder builder = new Notification.Builder(this);
//        builder.setSmallIcon(R.mipmap.ic_launcher);
//        builder.setContentText("this is a notification");
//        builder.setContentTitle("Notification");
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            builder.setChannelId("channelOne");
//        }
//        builder.setWhen(System.currentTimeMillis());
//        Notification notification = builder.build();
//        startForeground(1, notification);
        Log.d(TAG, "onCreate");
    }


    /**
     *
     * @param intent
     * @param flags
     * @param startId 每次回调onStartCommand()方法时，参数“startId”的值都是递增的，startId用于唯一标识每次对Service发起的处理请求
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");

        //有问题
        //直接在这里执行很多耗时操作, 超过了20s 秒后就将导致崩溃

        //开启子线程没有问题
        new Thread(new Runnable() {
            @Override
            public void run() {

                //test sleep 25s
                try {
                    Thread.sleep(30000);
                    Log.d(TAG, "child thread sleep 10s");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();

//        boolean s = true;
//        while (s){
//            Log.d(TAG, "ANR is coming");
//        }



        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind");
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }


    class MyBinder extends Binder{

        public void service_connect_activity(){

            Log.d(TAG, "Serice is connect to Activity, and exec this function");
        }
    }
}
